using System.Collections.Generic;
using System.IO;
using System.Text;

namespace System.Utility.Win32
{
	public class IniConfig
	{
		private string _FilePath;

		public IniConfig(string filePath)
		{
			_FilePath = filePath;
		}

		public bool ExistINIFile()
		{
			return File.Exists(_FilePath);
		}

		public string IniReadValue(string Section, string Key, string sdef = "")
		{
			if (!ExistINIFile())
			{
				throw new Exception("指定的配置文件读写错误！");
			}
			StringBuilder stringBuilder = new StringBuilder(500);
			Win32.GetPrivateProfileString(Section, Key, sdef, stringBuilder, 500, _FilePath);
			string str = stringBuilder.ToString().Trim().Replace(",", string.Empty);
			return str;
		}

		public void IniWriteValue(string Section, string Key, string Value)
		{
			if (!ExistINIFile())
			{
				throw new Exception("指定的配置文件读写错误！");
			}
			Win32.WritePrivateProfileString(Section, Key, Value, _FilePath);
		}

		public List<string> ReadAllSection()
		{
			List<string> strs = new List<string>();
			try
			{
				long length = (long)0;
				FileStream fileStream = new FileStream(_FilePath, FileMode.Open, FileAccess.Read);
				try
				{
					length = fileStream.Length;
				}
				finally
				{
					if (fileStream != null)
					{
						((IDisposable)fileStream).Dispose();
					}
				}
				byte[] numArray = new byte[(int) checked((IntPtr)length)];
				uint privateProfileString = Win32.GetPrivateProfileString(null, null, null, numArray, (uint)numArray.Length, _FilePath);
				int num = 0;
				for (int i = 0; (long)i < (long) privateProfileString; i++)
				{
					if (numArray[i] == 0)
					{
						strs.Add(Encoding.Default.GetString(numArray, num, i - num));
						num = i + 1;
					}
				}
			}
			catch
			{
				throw new Exception("指定的配置文件读写错误！");
			}
			return strs;
		}

		public Dictionary<string, string> ReadSectionKeys(string section)
		{
			Dictionary<string, string> strs = new Dictionary<string, string>();
			try
			{
				long length = (long)0;
				FileStream fileStream = new FileStream(_FilePath, FileMode.Open, FileAccess.Read);
				try
				{
					length = fileStream.Length;
				}
				finally
				{
					if (fileStream != null)
					{
						((IDisposable)fileStream).Dispose();
					}
				}
				byte[] numArray = new byte[(int) checked((IntPtr)length)];
				uint privateProfileString = Win32.GetPrivateProfileString(section, null, null, numArray, (uint)numArray.Length, _FilePath);
				int num = 0;
				for (int i = 0; (long)i < (long) privateProfileString; i++)
				{
					if (numArray[i] == 0)
					{
						string str = Encoding.Default.GetString(numArray, num, i - num);
						string str1 = IniReadValue(section, str, _FilePath);
						strs.Add(str, str1);
						num = i + 1;
					}
				}
			}
			catch
			{
				throw new Exception("指定的配置文件读写错误！");
			}
			return strs;
		}
	}
}